package com.excesys.exsecs.alarm.judgment;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.excesys.exsecs.alarm.dto.AlarmEnableDto;
import com.excesys.exsecs.alarm.dto.RunFlyOrLow;
import com.excesys.exsecs.alarm.entity.AlarmEnableBind;
import com.excesys.exsecs.alarm.entity.AlarmRecord;
import com.excesys.exsecs.alarm.entity.AlarmTypeConf;
import com.excesys.exsecs.alarm.service.AlarmEnableService;
import com.excesys.exsecs.alarm.service.AlarmRecordService;
import com.excesys.exsecs.alarm.service.AlarmTypeConfService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
public class JudgmentInvoke {
	@Autowired
	private AlarmRecordService service;
	@Autowired
	private AlarmEnableService alarmEnableService;
	@Autowired
	private AlarmTypeConfService alarmTypeConfServicel;

	public void inovke(RunFlyOrLow runFlyOrLow){
		AlarmTypeConf alarmTypeConf = new AlarmTypeConf();
		AlarmRecord alarmRecord = new AlarmRecord();
		BeanUtils.copyProperties(runFlyOrLow,alarmRecord);
		AlarmEnableDto alarmEnableDto =	alarmEnableService.getInfoByName(runFlyOrLow.getByName());
		if(ObjectUtil.isNotEmpty(alarmEnableDto)){
			if("1".equals(alarmEnableDto.getOpenOrClose())){
				if (CollectionUtils.isNotEmpty(alarmEnableDto.getAlarmEnableBindList())){
					Optional<AlarmEnableBind> first = alarmEnableDto.getAlarmEnableBindList().stream().filter(it -> it.getFlag().equals(runFlyOrLow.getFlag())).findFirst();
					if (first.isPresent()){
						alarmTypeConf = alarmTypeConfServicel.getTypeByCode(first.get().getTypeCode());
					}
				}
				alarmRecord.setTimePartition(Integer.parseInt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM"))));
				alarmRecord.setAlarmTypeCode(alarmTypeConf.getTypeCode());
				alarmRecord.setAlarmContent(alarmTypeConf.getTypeName());
				service.save(alarmRecord);
			}
		}
	}

}
